package com.dhcc.DRGsHosp.facade.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.jws.WebService;

import org.dayatang.querychannel.JdbcTemplateObj;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.DRGVersionApplication;
import com.dhcc.DRGsHosp.application.DRGsApplication;
import com.dhcc.DRGsHosp.application.DrgCommonApplication;
import com.dhcc.DRGsHosp.application.DrgsIndexCalApplication;
import com.dhcc.DRGsHosp.application.SystemConfigApplication;
import com.dhcc.DRGsHosp.core.domain.DRGVersion;
import com.dhcc.DRGsHosp.facade.GroupServiceFacade;
import com.dhcc.DRGsHosp.facade.MrDataExportService;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.dhcc.DRGsHosp.infra.util.StringUtils;
import com.dhcc.checklicense.CheckLicenseTools;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @title		:MrDataExportServiceImpl.java
 * @description	:DRG数据导出接口
 * @author		:lileizheng
 * @date		:2018年10月23日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
@WebService(endpointInterface="com.dhcc.DRGsHosp.facade.MrDataExportService", serviceName="MrDataExportService",targetNamespace="MrDataExportService")
public class MrDataExportServiceImpl implements MrDataExportService{

	@Autowired  
    private JdbcTemplateObj jdbcTemplateObj;
	
	@Autowired
	private GroupServiceFacade groupServiceFacade;
	
	@Autowired
	private DRGsApplication drgsApplication;	
	
	private Map<String, Object> drgInfo;
	
	@Autowired
	private DrgsIndexCalApplication drgsIndexCalApplication;
	
	@Autowired
	private SystemConfigApplication systemConfigApplication;
	@Autowired
	private DRGVersionApplication drgVersionApplication;
	@Autowired
	private DrgCommonApplication drgCommonApplication;
	
	
	@Override
	public String drgGroupExport(String data, String isICDMatch) {
		try {
			String lmsg = CheckLicenseTools.checkLicense();
			if(!"success".equals(lmsg)){
				return "{result_code:-1, result_message: \""+lmsg+"\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "{result_code:-1, result_message: \"验证授权文件出错了:"+e.toString()+"\"}";
		}
		
		try {
			//获取DRG代码, 名称, 权重等信息
			if(drgInfo==null||drgInfo.isEmpty()){
				//获取最近分组使用的版本号和标杆id
				String asId;
				String verCode="";
				String dateFrom = systemConfigApplication.getMaxGroupYear();
				dateFrom = DrgsIndex.formateDateFrom(dateFrom);
				String dateTo = DrgsIndex.formateDateFrom(dateFrom);
				String roleCode=StringUtils.stringToAscii("医政").replaceAll(",", "");
				String userCode="yizheng";
			    //获取分组分案cn或bj 和标杆类型 
				String mouldeId="groupScheme_"+userCode+"_"+roleCode;
				String groupSchemeBenchType = systemConfigApplication.getSystemGroupScheme(mouldeId,userCode, roleCode);
				if(StringUtils.hasLength(groupSchemeBenchType)) {
					String gbStr[]=groupSchemeBenchType.split("θ");	
					//获取分组器版本号
					List<Map<String, Object>> list=drgsIndexCalApplication.checkVerVersion(gbStr[0],dateFrom,dateTo);
					
					if(!list.isEmpty()&&list.get(0).get("VER_CODE")!=null){
						verCode=list.get(0).get("VER_CODE").toString();
					}
					//获取标杆年分
					String stdYear=drgsIndexCalApplication.getStdYear(gbStr[1],verCode,dateTo.substring(0, 4));
					asId = verCode+"_"+gbStr[1]+"_"+stdYear;
				}else {
					asId = null;
				} 
				List<Map<String, Object>> drgList = drgsApplication.findDRGInfo(asId, verCode);
				drgInfo = new HashMap<>();
				for(Map<String, Object> drg: drgList){
					if(drg.get("DRG_CODE")!=null){
						drgInfo.put(drg.get("DRG_CODE").toString(), drg);
					}
				}
			}
			//分组器版本号
			String groupVersion = GlobalData.sysConfig.get("GROUP_VER");
			String icdVerCode=drgCommonApplication.getIcdVerCodeByGroupVersion(groupVersion);
			String [] icd=icdVerCode.split(",");
			//诊断编码版本
			String icdDiaVerConfig = icd[1]+"";;
			//手术操作版本
			String icdOperVerConfig =icd[0]+"";
			ObjectMapper objectMapper = new ObjectMapper();
			//传入分组器的参数
			Map<String, Object>  patient = new HashMap<>();
			Map<String, Object>  patientData = objectMapper.readValue(data, Map.class);
			//需要将 patientData转化为分组器的真正参数
			//随机生成6位数字代替病案号
			patient.put("B_WT4_V1_ID", (int)((Math.random()*9+1)*100000)+"");
			//年龄
			patient.put("AGE",patientData.get("AGE") );
			//性别
			patient.put("GENDER", patientData.get("GENDER"));
			//总费用
			patient.put("TOTAL_EXPENSE", patientData.get("TOTAL_EXPENSE"));
			//主要诊断
			patient.put("DISEASE_CODE", patientData.get("DISEASE_CODE"));
			//住院天数
			patient.put("ACCTUAL_DAYS", patientData.get("ACCTUAL_DAYS"));
			//新生儿年龄
			patient.put("SF0100",patientData.get("NEWBORN_AGE"));
			//新生儿体重
			patient.put("SF0102", patientData.get("NEWBORN_WEIGHT"));
			//呼吸机使用时间
			patient.put("SF0104", patientData.get("BREAT_TIME"));
			//其他诊断
			patient.put("DIAGS_CODE", patientData.get("DIAGS_CODE"));
			//手术
			patient.put("OPERS_CODE", patientData.get("OPERS_CODE"));
			//离院方式
			patient.put("SF0104", patientData.get("BREAT_TIME"));
			//首页ID
			patient.put("CASE_ID", UUID.randomUUID());
			String groupVer = patientData.get("VER_CODE")!=null?patientData.get("VER_CODE").toString():null;
			//获取分组器地址
			String groupAddr ="";
			if(groupVer!=null&&groupVer.indexOf("北京2016版")>=0){
				groupAddr=GlobalData.sysConfig.get("GROUP_ADDER_2016");
			}else{
				groupAddr=GlobalData.sysConfig.get("GROUP_ADDER");
			}
			if(!StringUtils.hasLength(groupAddr)){
				return "{result_code:-1, result_message: \"请配置"+groupVer+"分组器地址\"}";
			}
			String groupVerCode = GlobalData.sysConfig.get("GROUP_VER");
			if(StringUtils.hasLength(groupVerCode)){
				//分组器版本号
				DRGVersion drgVersion=drgVersionApplication.getDRGVersion(groupVerCode);
				if(drgVersion!=null){
					//诊断编码版本
					icdDiaVerConfig = drgVersion.getIcd10Version();
					//手术操作版本
					icdOperVerConfig =drgVersion.getIcd9Version();
				}
			}
			//根据主要诊断亚目查询病种分值
			String diagCode=patientData.get("DISEASE_CODE")!=null?patientData.get("DISEASE_CODE").toString().toUpperCase():null;
			String diseaseScore=diagCode!=null?getDiseaseScore(diagCode.substring(0, 5)):"诊断未识别！";
			if(diseaseScore==null) {
				diseaseScore="不在A表范围";
			}
			//处理数据
			Map<String, Object> mrInfoMap=groupServiceFacade.dataGenerate(patient,groupVer,isICDMatch,icdDiaVerConfig,icdOperVerConfig);;
			//分组器调用,是否再分组，传入false		
			Map<String,Object> resultMap=groupServiceFacade.group(mrInfoMap,groupAddr,groupVer,false);
			Map<String, Object> result = new HashMap<>();
			if(drgInfo.get(resultMap.get("drg"))!=null){
				result = (Map<String, Object>) drgInfo.get(resultMap.get("drg"));
				result.put("Disease_Score", diseaseScore);
			}else{
				result.put("DRG_CODE", resultMap.get("drg"));
				result.put("Disease_Score", diseaseScore);
			}
			return "{result_code:0, result_message: \""+objectMapper.writeValueAsString(result)+"\"}";
		} catch (Exception e) {
			e.printStackTrace();
			return "{result_code:-1, result_message: \"分组报错了:"+e.toString()+"\"}";
		}
	}
	/**
	 * 
	 *  @Description：获取病种分值
	 *  @Author ChengBao  
	 *  @see com.dhcc.DRGsHosp.application.MrDataExportService#getDiseaseScore()
	 */
	public String getDiseaseScore(String diag) {
		String diseaseScore=jdbcTemplateObj.queryForObject("select fz from drgs.t_dict_a_fz t where t.icd10_subcode='"+diag+"'", String.class);
		return diseaseScore;
	}
}
